package o2o.web.actions.order.user;

import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.order.OrderGoodsMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.user.UserInfoExtraMemory;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.order.ORDER_STATUS;
import o2o.dao.PO.order.OrderGoods;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.order.USER_ORDER_FILTER;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.user.UserInfoExtra;
import o2o.dao.VO.order.OrderGoodsVO;
import o2o.dao.VO.order.REFUND_APPLY_STATUS;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.order.OrderMan;
import org.springframework.beans.BeanUtils;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

public class UserOrderMan {


    // 获取用户是否有订单
    public static boolean userHasOrder(String username) {
        if (ValidateUtil.isNull(username)) {
            return true;
        }

        UserInfoExtra userInfoExtra = UserInfoExtraMemory.getInstance().getByUsername(username);
        if (null == userInfoExtra) {
            return false;
        }
        if (null != userInfoExtra.getHasOrder() && userInfoExtra.getHasOrder() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 用户是否有折扣订单
     *
     * @param username
     * @return
     */
    public static boolean userHasDiscountOrder(String username) {
        if (ValidateUtil.isNull(username)) {
            return true;
        }

        UserInfoExtra userInfoExtra = UserInfoExtraMemory.getInstance().getByUsername(username);
        if (null == userInfoExtra) {
            return false;
        }
        if (null != userInfoExtra.getHasDiscountOrder() && userInfoExtra.getHasDiscountOrder() > 0) {
            return true;
        }
        return false;
    }


    // 用户有订单
    public static void doUserOrder(String username, String opUsername) {
        String userN = "";
        String userD = "";
        String userU = "";
        if (ValidateUtil.isNotNull(username)) {
            userN = " and b.username = '" + username + "' ";
            userD = " where username = '" + username + "' ";
            userU = " and username = '" + username + "' ";
        }
        StringBuffer sbDel = new StringBuffer();
        sbDel.append("UPDATE ").append(PojoTables.USER_INFO_EXTRA).append(" SET hasOrder = 0 ").append(userD);

        // 更新所有用户
        StringBuffer sbUpdate = new StringBuffer();
        sbUpdate.append("update (select count(orderno) counts,username ")
                .append(" from ").append(PojoTables.OrderInfo)
                .append(" where delFlag = 0 ").append(userU)
                .append(" and orderstatus != ").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append(" and orderstatus != ")
                .append(ORDER_STATUS.CANCEL).append(" and orderstatus != ").append(ORDER_STATUS.PAYED_CANCEL).append(" GROUP BY username ")
                .append(" ) a,")
                .append(PojoTables.USER_INFO_EXTRA).append(" b")
                .append(" set b.hasorder = 1")
                .append(" where a.counts >0 ")
                .append(userN)
                .append(" and a.username = b.username ");

        StringBuffer sbInsert = new StringBuffer();
        sbInsert.append(" insert into ").append(PojoTables.USER_INFO_EXTRA)
                .append(" (username,hasOrder,delFlag,createTime,createUser)")
                .append(" select a.username,1,0,").append(DateUtils.getCurrTime()).append(",'").append(opUsername)
                .append("' from (")
                .append(" select count(orderno) counts,username ").append(" from ").append(PojoTables.OrderInfo).append(" b ")
                .append(" where delFlag = 0 and orderstatus != ").append(ORDER_STATUS.CANCEL_BY_SYSTEM)
                .append(" and orderstatus != ").append(ORDER_STATUS.CANCEL).append(" and orderstatus != ").append(ORDER_STATUS.PAYED_CANCEL)
                .append(userN)
                .append(" GROUP BY username").append(" ) a")
                .append(" left join ").append(PojoTables.USER_INFO_EXTRA).append(" b on a.username = b.username ")
                .append(" where b.id is null and a.counts >0 ");

        StringBuffer sbUpdateDiscount = new StringBuffer();
        sbUpdateDiscount.append("update (select count(orderno) counts,username ")
                .append(" from ").append(PojoTables.OrderInfo)
                .append(" where delFlag = 0 ").append(userU).append(" and  (isFreeGoodOrder =1 or isDiscountOrder = 1 ) ")
                .append(" and orderstatus != ").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append(" and orderstatus != ")
                .append(ORDER_STATUS.CANCEL).append(" and orderstatus != ").append(ORDER_STATUS.PAYED_CANCEL).append(" GROUP BY username ")
                .append(" ) a,")
                .append(PojoTables.USER_INFO_EXTRA).append(" b")
                .append(" set b.hasDiscountOrder = 1")
                .append(" where a.counts >0 ")
                .append(userN)
                .append(" and a.username = b.username ");
        StringBuffer sbDiscount = new StringBuffer();
        sbDiscount.append("UPDATE ").append(PojoTables.USER_INFO_EXTRA).append(" SET hasDiscountOrder = 0 ").append(userD);

        System.out.println(sbDel.toString());
        System.out.println(sbUpdate.toString());
        System.out.println(sbInsert.toString());
        try {
            UserDaoSql.getInstance().executeUpdateBySql(sbDel.toString());
            UserDaoSql.getInstance().executeUpdateBySql(sbUpdate.toString());
            UserDaoSql.getInstance().executeUpdateBySql(sbInsert.toString());
            if (SYS_SETTINGS.IS_OPEN_DISCOUNT_EXCHANGE_CODE == 1) {
                // 更新是否有折扣订单
                UserDaoSql.getInstance().executeUpdateBySql(sbDiscount.toString());
                UserDaoSql.getInstance().executeUpdateBySql(sbUpdateDiscount.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


        if (ValidateUtil.isNotNull(username)) {
            UserInfoExtraMemory.getInstance().addOrModify(username);
        } else {
            UserInfoExtraMemory.getInstance().run();
        }
    }

    // 获取用户端的订单
    public static Map<String, Integer> getOrderCountByType(String sysAppKey, UserInfo user, Set<Integer> orderTypeSet) {
        List<String> listOfUser = OrderInfoMemory.getInstance().listOfUser(user.getUsername());
        Map<Integer, Set<String>> map = new HashMap<>();
        if (ValidateUtil.isAbsList(listOfUser)) {
            for (String orderNo : listOfUser) {
                OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
                if (orderInfo == null) {
                    continue;
                }
                if ((orderTypeSet != null && !orderTypeSet.isEmpty()) && (orderInfo.getOrderType() == null || !orderTypeSet.contains(orderInfo.getOrderType()))) {
                    continue;
                }
                // 待评论
                if (orderInfo.getOrderStatus() == ORDER_STATUS.OVER && orderInfo.getIsComment() == 0) {
                    Set<String> set = map.get(USER_ORDER_FILTER.UN_COMMENT);
                    if (set == null) {
                        set = new HashSet<>();
                    }
                    set.add(orderNo);
                    map.put(USER_ORDER_FILTER.UN_COMMENT, set);
                }
                // 待支付
                if (orderInfo.getOrderStatus() == ORDER_STATUS.SUBMIT && orderInfo.getIsPaid() == 0) {
                    Set<String> set = map.get(USER_ORDER_FILTER.TO_BE_PAID);
                    if (set == null) {
                        set = new HashSet<>();
                    }
                    set.add(orderNo);
                    map.put(USER_ORDER_FILTER.TO_BE_PAID, set);
                }
                // 退款单
                if (orderInfo.getIsRefundApply() == REFUND_APPLY_STATUS.APPLY
                        || orderInfo.getIsRefundApply() == REFUND_APPLY_STATUS.PASS
                        || orderInfo.getIsPartCancelApply() == REFUND_APPLY_STATUS.PASS
                        || ((orderInfo.getIsPartCancelApply() == REFUND_APPLY_STATUS.APPLY)
                        && orderInfo.getOrderStatus() != ORDER_STATUS.OVER
                        && orderInfo.getOrderStatus() != ORDER_STATUS.POSTMAN_FINISH
                        && orderInfo.getOrderStatus() != ORDER_STATUS.SHOP_FINISH)
                ) {
                    Set<String> set = map.get(USER_ORDER_FILTER.BEAK_ORDER);
                    if (set == null) {
                        set = new HashSet<>();
                    }
                    set.add(orderNo);
                    map.put(USER_ORDER_FILTER.BEAK_ORDER, set);
                }
                // 待取货
                if (orderInfo.getOrderStatus() == ORDER_STATUS.PAYED
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_SURE
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_READY
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_DAODIAN
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_ZHIDING
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_ZD_SURE_BEFORE_SHOP
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_REFUSED
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_SUER
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_DAODIAN
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_INNER_SHOP) {
                    Set<String> set = map.get(USER_ORDER_FILTER.WAITING_FOR_PICK);
                    if (set == null) {
                        set = new HashSet<>();
                    }
                    set.add(orderNo);
                    map.put(USER_ORDER_FILTER.WAITING_FOR_PICK, set);
                }
                //
                if (orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_PUSH_GOODS
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_PULL_GOODS
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_PICK_POINT
                        || orderInfo.getOrderStatus() == ORDER_STATUS.PEISONG
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_FINISH
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_PULL_GOODS) {
                    Set<String> set = map.get(USER_ORDER_FILTER.WAITING_FOR_POST);
                    if (set == null) {
                        set = new HashSet<>();
                    }
                    set.add(orderNo);
                    map.put(USER_ORDER_FILTER.WAITING_FOR_POST, set);
                }
            }
        }
        Map<String, Integer> dataMap = new HashMap<>();
        if (map.get(USER_ORDER_FILTER.UN_COMMENT) != null) {
            Set<String> set = map.get(USER_ORDER_FILTER.UN_COMMENT);
            dataMap.put("unComment", set.size());
        } else {
            dataMap.put("unComment", 0);
        }

        if (map.get(USER_ORDER_FILTER.WAITING_FOR_PICK) != null) {
            Set<String> set = map.get(USER_ORDER_FILTER.WAITING_FOR_PICK);
            dataMap.put("waitingForDelivery", set.size());
        } else {
            dataMap.put("waitingForDelivery", 0);
        }
        if (map.get(USER_ORDER_FILTER.WAITING_FOR_POST) != null) {
            Set<String> set = map.get(USER_ORDER_FILTER.WAITING_FOR_POST);
            dataMap.put("waitingForPost", set.size());
        } else {
            dataMap.put("waitingForPost", 0);
        }
        if (map.get(USER_ORDER_FILTER.TO_BE_PAID) != null) {
            Set<String> set = map.get(USER_ORDER_FILTER.TO_BE_PAID);
            dataMap.put("waitingForPay", set.size());
        } else {
            dataMap.put("waitingForPay", 0);
        }
        return dataMap;
    }

    // 获取骑手端订单列表信息
    public static Map<String, Integer> getPostmanOrderCountByType(String postmanUsername, Set<Integer> orderTypeSet) {
        List<String> listOfPostman = OrderInfoMemory.getInstance().listOfPostman(postmanUsername);
        Map<Integer, Set<String>> map = new HashMap<>();
        if (ValidateUtil.isAbsList(listOfPostman)) {
            for (String orderNo : listOfPostman) {
                OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
                if (orderInfo == null) {
                    continue;
                }
                if ((orderTypeSet != null && !orderTypeSet.isEmpty()) && (orderInfo.getOrderType() == null || !orderTypeSet.contains(orderInfo.getOrderType()))) {
                    continue;
                }
                // 待评论
                if (orderInfo.getOrderStatus() == ORDER_STATUS.OVER && orderInfo.getIsComment() == 0) {
                    Set<String> set = map.get(USER_ORDER_FILTER.ORDER_FINISH);
                    if (set == null) {
                        set = new HashSet<>();
                    }
                    set.add(orderNo);
                    map.put(USER_ORDER_FILTER.ORDER_FINISH, set);
                }

                // 待取货
                if ((orderInfo.getIsRefundApply() != REFUND_APPLY_STATUS.PASS) && (orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_ZD_SURE_BEFORE_SHOP
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_DAODIAN
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_SUER
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_DAODIAN
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_READY
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP)) {
                    Set<String> set = map.get(USER_ORDER_FILTER.WAITING_FOR_PICK);
                    if (set == null) {
                        set = new HashSet<>();
                    }
                    set.add(orderNo);
                    map.put(USER_ORDER_FILTER.WAITING_FOR_PICK, set);
                }
                // 待配送
                if ((orderInfo.getIsRefundApply() != REFUND_APPLY_STATUS.PASS) && (orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_PULL_GOODS
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_ARRIVED
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_PUSH_GOODS
                        || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_RECEIVING_PASSENGER
                        || orderInfo.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_PULL
                        || orderInfo.getOrderStatus() == ORDER_STATUS.PEISONG)) {
                    Set<String> set = map.get(USER_ORDER_FILTER.WAITING_FOR_POST);
                    if (set == null) {
                        set = new HashSet<>();
                    }
                    set.add(orderNo);
                    map.put(USER_ORDER_FILTER.WAITING_FOR_POST, set);
                }
            }
        }
        Map<String, Integer> dataMap = new HashMap<>();

        if (map.get(USER_ORDER_FILTER.WAITING_FOR_PICK) != null) {
            Set<String> set = map.get(USER_ORDER_FILTER.WAITING_FOR_PICK);
            dataMap.put("waitingForPick", set.size());
        } else {
            dataMap.put("waitingForPick", 0);
        }
        if (map.get(USER_ORDER_FILTER.WAITING_FOR_POST) != null) {
            Set<String> set = map.get(USER_ORDER_FILTER.WAITING_FOR_POST);
            dataMap.put("waitingForPost", set.size());
        } else {
            dataMap.put("waitingForPost", 0);
        }
        return dataMap;
    }

    // 获取指定订单号下的订单商品列表 以及子订单商品信息
    public static List<OrderGoodsVO> listOfOrderGoodsByOrderNo(String orderNo) {
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (info == null) {
            return Collections.emptyList();
        }
        List<OrderGoods> reList = new ArrayList<>();
        if (OrderMan.isMultipleParentOrder(info)) {
            HashSet<String> orderSet = OrderInfoMemory.getInstance().listOfParentOrderNo(info.getOrderNo());
            if (orderSet != null) {
                for (String or : orderSet) {
                    List<OrderGoods> goods = OrderGoodsMemory.getInstance().listOfOrderNo(or);
                    if (ValidateUtil.isAbsList(goods)) {
                        reList.addAll(goods);
                    }
                }
            }
        } else {
            reList = OrderGoodsMemory.getInstance().listOfOrderNo(orderNo);
        }
        if (ValidateUtil.isAbsList(reList)) {
            return reList.stream().map(b -> {
                OrderGoodsVO vo = new OrderGoodsVO();
                BeanUtils.copyProperties(b, vo);
                if (ValidateUtil.isNotNull(vo.getImageUrl()) && ValidateUtil.isNotNetUrl(vo.getImageUrl())) {
                    vo.setImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getImageUrl());
                }
                return vo;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
}
